const path = require("path")
const fs = require("fs")
const images = [".svg", ".png", ".jpg", ".jpeg"]
function readPictures(dir) {
    function readAllFiles(dir, prefix = "./") {
        return fs.readdirSync(dir).reduce((acc, one) => {
            const filePath = path.join(dir, one)
            const stat = fs.statSync(filePath)
            const fileName = path.basename(one)
            const ext = path.extname(one)
            if (stat.isFile() && images.includes(ext)) {
                acc.push({
                    path: path.join(prefix, one),
                    fileName,
                    prefix,
                    modifyTime: stat.mtimeMs,
                })
            } else if (stat.isDirectory()) {
                acc.push(...readAllFiles(filePath, path.join(prefix, one)))
            }
            return acc
        }, [])
    }

    return readAllFiles(dir)
        .reduce((acc, one) => {
            const found = acc.find((v) => v.prefix == one.prefix)
            if (found) {
                found.files.push(one)
                if (one.modifyTime > found.modifyTime) {
                    found.modifyTime = one.modifyTime
                }
            } else {
                acc.push({
                    prefix: one.prefix,
                    files: [one],
                    modifyTime: one.modifyTime,
                })
            }
            return acc
        }, [])
        .sort((a, b) => b.modifyTime - a.modifyTime)
        .map((one) => {
            const date = new Date(one.modifyTime)
            return `<div><div>${one.prefix} <span class="time">${
                date.getFullYear() === new Date().getFullYear()
                    ? ""
                    : date.getFullYear() + "-"
            }${
                date.getMonth() + 1
            }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}</span></div>${one.files
                .map((one) => {
                    return `<img src="${one.path}" onclick="showSrc(this)" title="${one.path}"/>`
                })
                .join("\n")}</div>`
        })
        .join("\n")
}
module.exports = readPictures
